<template>
  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form size="" :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input v-model="formInline.nick_name" placeholder="请输入昵称|手机号|ID"></el-input>
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="formInline.grade_id" placeholder="请选择">
            <el-option label="全部" value="0"></el-option>
            <el-option v-for="(item, index) in gradeList" :key="index" :label="item.name" :value="item.grade_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="老板账号">
          <el-select v-model="formInline.factory_boss" placeholder="请选择" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="财务账号">
          <el-select v-model="formInline.is_finance" placeholder="请选择" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区管理">
          <el-select v-model="formInline.region_manager" placeholder="请选择" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属地区">
          <el-cascader v-model="formInline.region_id" :options="regions"
            :props="{ label: 'name', value: 'id', checkStrictly: true }" clearable @change="changeRegion" />
        </el-form-item>
        <el-form-item label="厂家">
          <el-select v-model="formInline.carfilm_factory" placeholder="请选择" clearable>
            <el-option v-for="(item, index) in factories" :key="index" :label="item.factory_name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker v-model="formInline.reg_date" type="daterange" value-format="YYYY-MM-DD" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="Plus" @click="editClick('add')" v-auth="'/user/user/add'">新增会员</el-button>
        </el-form-item>
      </el-form>
      <div class="mb16">
        <span>标签</span>
        <span class="pl10">
          <el-radio-group v-model="formInline.tag_id" size="" @change="onSubmit">
            <el-radio-button :value="0">全部</el-radio-button>
            <el-radio-button :value="item.tag_id" v-for="(item, index) in allTag" :key="index">
              {{ item.tag_name }}
            </el-radio-button>
          </el-radio-group>
        </span>
      </div>
      <div style="display: flex">
        <el-button type="primary" icon="Setting" @click="handleFactory" v-auth="'/carfilm/factory/user'"
          :disabled="!selectedRows.length">批量设置厂家</el-button>
        <el-button type="primary" icon="Setting" @click="handleRegion"
          :disabled="!selectedRows.length">批量设置地区</el-button>
        <el-button type="primary" icon="Setting" @click="handleTag" :disabled="!selectedRows.length">批量设置标签</el-button>
      </div>
    </div>
    <!--内容-->
    <div class="product-content" style="margin-top: 10px">
      <div class="table-wrap">
        <el-table size="" :data="tableData" border height="calc(100vh - 350px)" style="width: 100%" v-loading="loading"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="user_id" label="ID" width="80"></el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="real_name" label="姓名"></el-table-column>
          <el-table-column prop="nickName" label="微信头像">
            <template #default="scope">
              <img v-img-url="scope.row.avatarUrl" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column prop="" label="会员等级">
            <template #default="scope">
              <span v-if="!scope.row.grade_id">无等级</span>
              <span v-else>{{ scope.row.grade?.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="来源">
            <template #default="scope">
              <span v-if="scope.row.reg_source == 'wx'">小程序</span>
              <span v-if="scope.row.reg_source == 'app'">APP</span>
              <span v-if="scope.row.reg_source == 'h5'">H5</span>
              <span v-if="scope.row.reg_source == 'mp'">公众号</span>
            </template>
          </el-table-column>
          <el-table-column prop="points" label="积分"></el-table-column>
          <el-table-column prop="balance" label="余额"></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
          <el-table-column label="推荐人">
            <template #default="scope">
              <span v-if="scope.row.referee_id == 0">--</span>
              <span v-else>{{
                scope.row.referer?.real_name
                  ? scope.row.referer?.real_name
                  : scope.row.referer?.nickName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="factory.factory_name" label="厂家" align="center">
            <template #default="scope">
              <p v-if="!scope.row.factory">--</p>
              <p v-else>{{ scope.row.factory?.factory_name }}</p>
              <el-tag type="warning" v-if="scope.row.factory_boss == 1">老板账号</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="注册时间" width="140"></el-table-column>
          <el-table-column fixed="right" label="操作" width="370" fixed-right>
            <template #default="scope">
              <el-button @click="addClick(scope.row)" link type="primary" size="" v-auth="'/user/user/recharge'">充值
              </el-button>
              <el-button @click="editClick('edit', scope.row)" link type="primary" size="" v-auth="'/user/user/edit'">编辑
              </el-button>
              <el-button @click="editClick('psw', scope.row)" link type="warning" size=""
                v-auth="'/user/user/edit'">修改密码
              </el-button>
              <el-button @click="gradeClick(scope.row)" link type="primary" size="" v-auth="'/user/user/grade'">等级
              </el-button>
              <el-button @click="tagClick(scope.row)" link type="primary" size="" v-auth="'/user/user/delete'">标签
              </el-button>
              <el-button @click="upClick(scope.row)" link type="warning" size="" v-auth="'user_set_referee'">修改上级
              </el-button>
              <el-button @click="deleteClick(scope.row)" link type="danger" size="" v-auth="'/user/user/delete'">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--分页-->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
          :current-page="curPage" :page-size="pageSize" layout="total, prev, pager, next, jumper,sizes"
          :page-sizes="[2, 10, 20, 50, 100, 200]" :total="totalDataNumber"></el-pagination>
      </div>
    </div>

    <!--会员充值-->
    <Recharge v-if="open_add" :open_add="open_add" :form="userModel" :gradeList="gradeList"
      @closeDialog="closeDialogFunc($event, 'add')"></Recharge>
    <!--会员等级-->
    <Grade v-if="open_edit" :open_edit="open_edit" :form="userModel" :gradeList="gradeList"
      @closeDialog="closeDialogFunc($event, 'edit')"></Grade>
    <!--会员标签-->
    <Tag v-if="open_tag" :open_tag="open_tag" :form="userModel" @closeDialog="closeDialogFunc($event, 'tag')"></Tag>
    <UserInfo ref="userInfoRef" @doneSave="getTableList"></UserInfo>
    <SetUp ref="setUpRef" @doneSave="getTableList"></SetUp>
    <Factory ref="factoryRef" @getTable="getTableList"></Factory>
    <el-dialog v-model="regionVisible" title="设置地区" width="30%">
      <div class="dialog-content">
        <el-cascader v-model="batchRegion" :options="regions" :props="{ label: 'name', value: 'id' }" clearable />
      </div>
      <template #footer>
        <el-button @click="regionVisible = false">取消</el-button>
        <el-button type="primary" @click="batchRegionSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, provide } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { userlist, deleteuser, batchUserRegion } from "@/api/user.js";
import Grade from "./dialog/Grade.vue";
import Recharge from "./dialog/Recharge.vue";
import Tag from "./dialog/Tag.vue";
import UserInfo from "./dialog/UserInfo.vue";
import SetUp from "./dialog/SetUp.vue";
import Factory from "./dialog/Factory.vue";
import { getInfoListAPi } from "@/api/carfilm/factory";
import { getRegionOption } from "@/api/utils";

// 引用子组件
const userInfoRef = ref<InstanceType<typeof UserInfo> | null>(null);
const setUpRef = ref<InstanceType<typeof SetUp> | null>(null);
const factoryRef = ref<InstanceType<typeof Factory> | null>(null);
const regionVisible = ref(false);
// 数据定义
const loading = ref(true);
const tableData = ref<any[]>([]);
const pageSize = ref(20);
const totalDataNumber = ref(0);
const curPage = ref(1);
const selectedRows = ref<any[]>([]);
const factories = ref<any[]>([]);
provide("factories", factories);
provide("selectedRows", selectedRows);
// 表单数据模型
const formInline = reactive({
  nick_name: "",
  grade_id: "",
  reg_date: "",
  tag_id: 0,
  reg_source: "",
  factory_boss: "",
  factory: "",
  carfilm_factory: "",
  is_finance: "",
  region_manager: "",
  region_id: "",
});
const batchRegion = ref([]);
// 弹窗控制
const open_add = ref(false);
const open_edit = ref(false);
const open_tag = ref(false);

// 当前编辑对象
const userModel = ref({});

// 等级和标签数据
const gradeList = ref<any[]>([]);
const allTag = ref<any[]>([]);

// 处理多选变化
const handleSelectionChange = (val: any[]) => {
  // 可根据需要实现多选逻辑
  selectedRows.value = val;
};
const handleFactory = () => {
  factoryRef.value?.open();
};

const handleRegion = () => {
  regionVisible.value = true;
}
const handleTag = () => {
  userModel.value = {
    user_id: selectedRows.value.map((item: any) => item.user_id),
  }
  open_tag.value = true;
};
// 分页相关方法
const handleCurrentChange = (val: number) => {
  curPage.value = val;
  loading.value = true;
  getTableList();
};

const handleSizeChange = (val: number) => {
  curPage.value = 1;
  pageSize.value = val;
  getTableList();
};

// 获取列表数据
const getTableList = () => {
  const Params = {
    ...formInline,
    page: curPage.value,
    list_rows: pageSize.value,
  };

  userlist(Params)
    .then((data: any) => {
      loading.value = false;
      tableData.value = data.data.list.data;
      totalDataNumber.value = data.data.list.total;
      gradeList.value = data.data.grade;
      allTag.value = data.data.allTag;
    })
    .catch((error: any) => {
      loading.value = false;
    });
};

// 搜索查询
const onSubmit = () => {
  loading.value = true;
  getTableList();
};

// 打开添加弹窗
const addClick = (item: any) => {
  userModel.value = item;
  open_add.value = true;
};

// 打开编辑弹窗
const editClick = (type: string, item?: any) => {
  const id = item?.user_id;
  userInfoRef.value?.open(type, id);
};

// 打开设置上级弹窗
const upClick = (row: any) => {
  setUpRef.value?.open([row]);
};

// 打开等级弹窗
const gradeClick = (item: any) => {
  userModel.value = item;
  open_edit.value = true;
};

// 打开标签弹窗
const tagClick = (item: any) => {
  userModel.value = item;
  open_tag.value = true;
};

// 关闭弹窗
const closeDialogFunc = (e: any, f: string) => {
  switch (f) {
    case "add":
      open_add.value = e.openDialog;
      if (e.type === "success") {
        getTableList();
      }
      break;
    case "edit":
      open_edit.value = e.openDialog;
      if (e.type === "success") {
        getTableList();
      }
      break;
    case "tag":
      open_tag.value = e.openDialog;
      if (e.type === "success") {
        getTableList();
      }
      break;
  }
};

// 删除用户
const deleteClick = (row: any) => {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      deleteuser({
        user_id: row.user_id,
      })
        .then((data: any) => {
          loading.value = false;
          if (data.code == 1) {
            ElMessage({
              message: "恭喜你，用户删除成功",
              type: "success",
            });
            getTableList();
          } else {
            loading.value = false;
          }
        })
        .catch((error: any) => {
          loading.value = false;
        });
    })
    .catch(() => {
      loading.value = false;
    });
};
const regions = ref<any[]>([]);
provide("regions", regions);
// 组件挂载后获取数据
onMounted(() => {
  getTableList();
  getInfoListAPi({}).then((res: any) => {
    factories.value = res.data.data;
  });
  getRegionOption().then((res: any) => {
    if (res.code == 1) {
      regions.value = res.data;
    }
  });
});
const changeRegion = (e: any) => {
  console.log(e);
  if (e != null && e.length > 0) {
    formInline.region_id = e[2] ?? (e[1] ?? e[0]);
  }
};
const batchRegionSubmit = () => {
  loading.value = true;
  console.log(batchRegion.value);
  batchUserRegion({
    region_id: batchRegion.value,
    user_ids: selectedRows.value.map((item: any) => item.user_id),
  })
    .then((res: any) => {
      if (res.code == 1) {
        ElMessage({
          message: "批量设置成功",
          type: "success",
        })
      }
    }).finally(() => {
      regionVisible.value = false;
      loading.value = false;
    })
}
</script>

<style scoped>
.mb16 {
  margin-bottom: 16px;
}

.pl10 {
  padding-left: 10px;
}
</style>
